package com.py.search.listener;

import com.alibaba.fastjson.JSON;
import com.py.common.constants.ArticleConstants;
import com.py.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 同步新文章到ES
 * @author pengy
 * @create 2022-11-20 20:53
 */
@Component
@Slf4j
public class ArticleSaveListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){
        log.info("收到消息",message);
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

        IndexRequest indexRequest = new IndexRequest("app_info_article")
                .id(searchArticleVo.getId().toString())
                .source(message,XContentType.JSON);

        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
